//
//  Ship.m
//  SpaceStorm
//
//  Created by 祥 雍 on 13-4-20.
//  Copyright (c) 2013年 __MyCompanyName__. All rights reserved.
//

#import "Ship.h"
#import "ShipModelInfoMgr.h"
#import "ShipInfo.h"
#import "ShipInfoMgr.h"
#import "MonsterInfo.h"
#import "MonsterInfoMgr.h"
#import "BattleScene.h"
#import "RotateWithAction.h"
#import "ChangeSpeedWithAction.h"

@implementation Ship

@synthesize shipId = _shipId;
@synthesize prop = _prop;
@synthesize isTeam = _isTeam;
@synthesize view = _view;
@synthesize weaponList = _weaponList;
@synthesize fsmManage = _fsmManage;

+(id) shipWithId:(int) shipId
{
     return [[[self alloc] initWithId:shipId] autorelease]; 
}

-(id) initWithId:(int) shipId
{
    self = [super init]; 
	
	if (self!= nil) 
    {
        //船舰信息
        ShipInfo* shipInfo = [[ShipInfoMgr sharedManager] getInfoById:shipId];
        if (shipInfo) 
        {
            //船舰属性
            struct ShipProp p = self.prop;
            p.name = shipInfo.name;
            p.icon = shipInfo.icon;
            p.curShield = p.maxShield = shipInfo.shield;
            p.curArmoured = p.maxArmoured = shipInfo.armoured;
            p.curHp = p.maxHp = shipInfo.hp;
            p.field = shipInfo.field;
            p.maxSpeed = shipInfo.speed;
            p.curSpeed = 0;
            p.accelerated = shipInfo.accelerated;
            p.steeringForce = shipInfo.steeringForce;
            
            //模型信息
            modelInfo = [[ShipModelInfoMgr sharedManager] getInfoById:shipInfo.modelId];
            
            if(modelInfo)//表信息存在
            {
                //视图,设置锚点
                self.view = [ShipView viewWithModelId:shipInfo.modelId anchorPoint:modelInfo.anchorPoint];
                [self addChild:self.view];
                //在船的属性里纪录下模型信息
                p.width = modelInfo.width;
                p.height = modelInfo.height;
                p.anchorPoint = modelInfo.anchorPoint;
            }
            else
            {
                CCLOG(@"船舰模型创建失败,查船舰模型表失败：%d", shipInfo.modelId);
            }
            
            //武器的数组
            self.weaponList = [CCArray array];
            self.prop = p;
            
            //状态机
            self.fsmManage = [ShipFSMManager managerWithShip:self];
            
            [self scheduleUpdate];
//            [self schedule:@selector(updateLogic:) interval:1 / 30];
        }
        else
        {
            CCLOG(@"船舰创建失败,查船舰表失败：%d", shipId);
        }
    }
    
    return self;
}

/**
	根据shipVo创建ship的实例
	@param shipVo 储存自己船信息的数据结构
	@returns 返回实例
 */
+(id) shipWithVo:(ShipVo*)shipVo
{
    return [[[self alloc] initWithVo:shipVo] autorelease];
}

/**
	根据shipVo初始化ship的实例
	@param shipVo 储存自己船信息的数据结构
	@returns 返回实例
 */
-(id) initWithVo:(ShipVo*)shipVo
{
    if(self=[super init])
    {
        if(shipVo != nil)
        {
            CCLOG(@"创建自己战舰:%@", shipVo.shipName);
            //查询船舰信息
            ShipInfo* shipInfo = [[ShipInfoMgr sharedManager] getInfoById:shipVo.shipId];
            if(shipInfo != nil)
            {
                //创建船舰
                [self initWithId:shipVo.shipId];
                
                //挂载攻击武器组
                NSMutableDictionary* attackSystemIds = shipVo.attackSystemIds;
                [self addAttackWeapons:attackSystemIds];
                
                //挂载防御武器组
                NSMutableDictionary* defenseSystemIds = shipVo.defenseSystemIds;
                [self addDttackWeapons:defenseSystemIds];
                
                //挂载辅助系统组
                NSMutableDictionary* servoSystemIds = shipVo.servoSystemIds;
                [self addServoSystems:servoSystemIds];
                
                //挂载舰载机组
                NSMutableDictionary* airplaneIds = shipVo.attackSystemIds;
                [self addAirplanes:airplaneIds];
            }
            else
            {
                CCLOG(@"创建自己船舰失败，shipId:%d", shipVo.shipId);
            }
        }
        else
        {
            CCLOG(@"shipVo为nil");
        }
    }
    
    return self;
}

/**
	根据怪物表id创建ship实例
	@param MonsterId 怪物表id
	@returns 返回实例
 */
+(id) shipWithMonsterId:(int)monsterId
{
    return [[[self alloc] initWithMonsterId:monsterId] autorelease];
}

/**
	根据怪物表Id初始化ship实例
	@param MonsterId 怪物表id
	@returns  返回实例
 */
-(id) initWithMonsterId:(int)monsterId
{
    if(self=[super init])
    {
        //先查询怪物组
        MonsterInfo* monsterInfo = [[MonsterInfoMgr sharedManager] getInfoById:monsterId];
        if(monsterInfo != nil)
        {
            CCLOG(@"创建敌方战舰:%@", monsterInfo.shipName);
            //查询船舰信息
            ShipInfo* shipInfo = [[ShipInfoMgr sharedManager] getInfoById:monsterInfo.baseShipName];
            if(shipInfo != nil)
            {
                //创建船舰
                [self initWithId:monsterInfo.baseShipName];
                
                //挂载攻击武器组
                NSMutableDictionary* attackSystemIds = monsterInfo.attackSystemIds;
                [self addAttackWeapons:attackSystemIds];
                
                //挂载防御武器组
                NSMutableDictionary* defenseSystemIds = monsterInfo.defenseSystemIds;
                [self addDttackWeapons:defenseSystemIds];
                
                //挂载辅助系统组
                NSMutableDictionary* servoSystemIds = monsterInfo.servoSystemIds;
                [self addServoSystems:servoSystemIds];
                
                //挂载舰载机组
                NSMutableDictionary* airplaneIds = monsterInfo.attackSystemIds;
                [self addAirplanes:airplaneIds];
            }
            else
            {
                CCLOG(@"创建敌方船舰失败，shipId:%d", monsterInfo.baseShipName);
            }
        }
        else
        {
            CCLOG(@"monster不存在，monsterId:%d", monsterId);
        }
    }
    
    return self;
}

/**
	添加武器
	@param weaponId 武器的装备Id
	@param index 武器位
 */
-(void) addAttackWeapon:(int)equipId index:(int)index
{
    Weapon* weapon;
    
    //根据船的模型表，查处炮位相关信息
    if(modelInfo)//表信息存在
    {
        CGRect posAndAngle = [modelInfo getPosAndAngle:WeaponAttack index:index];
        
        if(CGRectIsEmpty(posAndAngle) == YES)
        {
            CCLOG(@"炮位:%d不存在", index);
            
            return;
        }
        
        weapon = [Weapon weaponWithId:equipId];
        
        [self.weaponList addObject:weapon];
        
        //添加武器的模型
        weapon.position = posAndAngle.origin;
        
        [self addChild:weapon];
    }
}

/**
	添加攻击武器组
	@param weaponIds 攻击武器id的字典，index为key
 */
-(void) addAttackWeapons:(NSMutableDictionary*)equipIds
{
    for (NSString* key in  equipIds) 
    {
        NSNumber* equipId = [equipIds objectForKey:key];
        if (equipId) 
        {
            [self addAttackWeapon:[equipId intValue] index:[key intValue]];
        }
    }
}

/**
	添加防御武器
	@param weaponId 防御武器的查询Id
	@param index 武器位
 */
-(void) addDefenseWeapon:(int)equipId index:(int)index
{
    
}

/**
	添加防御武器组
	@param weaponIds 装备查找Id的字典，index为key
 */
-(void) addDttackWeapons:(NSMutableDictionary*)equipIds
{
    
}

/**
	添加辅助系统
	@param equipId 装备查找Id
 */
-(void) addServoSystem:(int)equipId

{
    
}

/**
	添加辅助系统组
	@param equipIds   装备查找id的字典，index为key
 */
-(void) addServoSystems:(NSMutableDictionary*)equipIds

{
    
}

/**
	添加舰载机
	@param airplaneId 舰载机的查询Id
 */
-(void) addAirplane:(int)equipId
{
    
}


/**
	添加舰载机组
	@param airplaneIds 舰载机id的字典，index为key
 */
#pragma mark -
#pragma mark test
-(void) addAirplanes:(NSMutableDictionary*)equipIds
{
    // TODO: ...
    // !!!: sss
}




/**
	每帧更新，画面刷新更新
	@param delta 
 */
-(void) update:(ccTime)delta
{
    //TODO
//    CCSpeed *speed=(CCSpeed*)[self getActionByTag:66]; 
//    float s = speed.speed;
//    s += 0.05;
//    [speed setSpeed:s];//放慢原有速度的0.5倍  
//    self.rotation = self.rotation + 0.2;
}

/**
	每1／30秒更新一次，逻辑更新
	@param delta 
 */
-(void) updateLogic:(ccTime)delta
{
    //没有目标点就不更新
    if(CGPointEqualToPoint(_targetPoint, CGPointZero)) return;
    
    struct ShipProp p = self.prop;
    
     //算出需要旋转到的角度
    float randomDegress = ccpToAngle(ccpSub(_targetPoint, self.position));
    float angleDegrees = 90 - CC_RADIANS_TO_DEGREES(randomDegress);
    
    //计算出夹角
    float angleDiff = angleDegrees - self.rotation;
    float angleNeed = 0;
    if(abs(angleDiff) > (p.steeringForce / 30))
    {
        angleNeed = (p.steeringForce / 30) * abs(angleDiff) / angleDiff;
    }
    else
    {
        angleNeed = angleDiff;
    }
    
    //改变角度
    if(angleNeed != 0)
    {
        self.rotation += angleNeed;
        CCLOG(@"更新角度：%f", self.rotation);
    }
    
//    return;
    
    //计算出本帧速度
    if(p.curSpeed < p.maxSpeed)
    {
        p.curSpeed += p.accelerated / 30;
        if(p.curSpeed > p.maxSpeed)
        {
            p.curSpeed = p.maxSpeed;
        }
    }
    
    //计算出速度分量
    float timelySpeed = cos(CC_DEGREES_TO_RADIANS(angleNeed)) * p.curSpeed / 30;
    
    //计算出要移动到得点
    CGPoint w = ccpForAngle(CC_DEGREES_TO_RADIANS(self.rotation));
    CGPoint t = ccpMult(w, timelySpeed);
    CGPoint posNeed =ccpAdd(self.position, t);
    
    //改变位置
    if(!CGPointEqualToPoint(self.position, _targetPoint))
    {
        float l = ccpLength(ccpSub(_targetPoint, self.position));
        CCLOG(@"距离：%f", l);
        if(l > timelySpeed)//距离够远
        {
            self.position = posNeed;
            CCLOG(@"更新位置：%f_%f", self.position.x, self.position.y);
        }
        else//本秒到底
        {
            self.position = _targetPoint;
            CCLOG(@"更新位置一步到位：%f_%f", self.position.x, self.position.y);
        }
    }
//    id ac1 = [CCMoveTo actionWithDuration:40 position:ccp(toPoint.x, toPoint.y)];
//    id actionCallFunc = [CCCallFunc actionWithTarget:self selector:@selector(doATask)];
//    [self runAction:[CCSequence actions:ac1, actionCallFunc, nil]]; 
    
    self.prop = p;
}

/**
 将船舰移动到指定的地点
	@param toPoint 目标点
 */
-(void) moveTo:(CGPoint)toPoint
{
    //开启尾焰
    [self.view showWakeFlame:YES];
    
    //开始移动
    //    _targetPoint = toPoint;
    
    //    id ac1 = [CCMoveTo actionWithDuration:10 position:toPoint];
    //    id ac2 = [CCSpeed actionWithAction:ac1 speed:2];
    //    [ac2 setTag:66];
    //    
    //    [self runAction:ac2];
    
    //    ccBezierConfig bezier; // 创建贝塞尔曲线  
    //    bezier.controlPoint_1 = ccp(0, 0); // 起始点  
    //    bezier.controlPoint_2 = ccp(0, 900); //控制点  
    //    bezier.endPosition = ccp(600, 600); // 结束位置     
    //    CCBezierTo *actionMove = [CCBezierTo actionWithDuration:10 bezier:bezier]; 
    //    RotateWithAction* rotateAction = [RotateWithAction actionWithAction:actionMove];
    //    [self runAction:rotateAction];
}

/**
	简单的移动，先转到正确的角度(匀速)，再
	@param toPoint 目标点
 */
-(void) moveToNormal:(CGPoint)toPoint
{
    //纪录目标点
    _targetPoint = toPoint;
    
    //开启尾焰
    [self.view showWakeFlame:YES];
    
    //算出需要旋转到的角度
    float randomDegress = ccpToAngle(ccpSub(_targetPoint, self.position));
    float angleDegrees = 90 - CC_RADIANS_TO_DEGREES(randomDegress);
    
    //计算出夹角
    float angleDiff = angleDegrees - self.rotation;
    //计算出旋转时间
    float rate = abs(angleDiff) / _prop.steeringForce;
    //添加旋转的动作
    id rotateAction = [CCRotateTo actionWithDuration:rate angle:angleDegrees];
    id actionCallFunc = [CCCallFunc actionWithTarget:self selector:@selector(doChangeSpeedMove)];
    [self runAction:[CCSequence actions:rotateAction, actionCallFunc, nil]];
}

-(void) doChangeSpeedMove
{
    //计算距离
    float distance = ccpDistance(self.position, _targetPoint);
    //计算出匀速需要的时间
    float constantRate = distance / _prop.maxSpeed;
    //计算出要加速的时间
    //计算出
    //添加变速动作
    id ac1 = [CCMoveTo actionWithDuration:constantRate position:_targetPoint];
    id actionCallFunc = [CCCallFunc actionWithTarget:self selector:@selector(doATask)];
    id sq = [CCSequence actions:ac1, actionCallFunc, nil];
    ChangeSpeedWithAction* ac2 = [ChangeSpeedWithAction actionWithAction:sq accSpeed:0.1 startSpeed:0 finishUpTime:10 startDowmTime:10];
    [self runAction:ac2];  
}


/**
	贝塞尔曲线移动，转向力作为控制点
	@param toPoint 要移动到的点
 */
-(void) moveToBezier:(CGPoint)toPoint
{
    //开启尾焰
    [self.view showWakeFlame:YES];
    
    //添加贝塞尔曲线移动的动作
    ccBezierConfig bezier; // 创建贝塞尔曲线  
    bezier.controlPoint_1 = ccp(0, 0); // 起始点1,不用  
    bezier.controlPoint_2 = ccp(0, 900); //控制点2 
    bezier.endPosition = ccp(600, 600); // 结束位置     
    CCBezierTo *actionMove = [CCBezierTo actionWithDuration:10 bezier:bezier]; 
    RotateWithAction* rotateAction = [RotateWithAction actionWithAction:actionMove];
    [self runAction:rotateAction];
}

-(void) doATask
{
    //关闭尾焰
    [self.view showWakeFlame:NO];
}

- (void) dealloc
{
    if(self.view)
    {
        [self.view release];
    }
    
    if(self.weaponList)
    {
        [self.weaponList release];
    }
    
	// don't forget to call "super dealloc"
	[super dealloc];
}

@end
